package com.example.managerment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.managerment.mapper.PermissionMapper;
import com.example.managerment.mapper.UsersMapper;
import com.example.managerment.module.dto.PermissionDTO;
import com.example.managerment.module.dto.UsersDTO;
import com.example.managerment.module.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
@Service("UserDetailsService")
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UsersMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Users users= userMapper.selectOne(new QueryWrapper<Users>().eq("account_name",s));

        if(StringUtils.isEmpty(users)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<PermissionDTO> permissionDTO = permissionMapper.getUserRolesByUserId(users.getUserId());



        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionDTO.stream().forEach(sysPermission -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+sysPermission.getRoleName());
            grantedAuthorities.add(grantedAuthority);
        });
        UsersDTO usersDetails = new UsersDTO(users.getAccountName(),users.getAccountPassword(),grantedAuthorities);
        usersDetails.setResource(permissionDTO);
        usersDetails.setUserId(users.getUserId());
        usersDetails.setAccountName(users.getAccountName());

        return usersDetails;
    }
}
